const fs = require('fs')
const path = require('path')
const shortid = require('shortid')
const axios = require('axios')

function getResponseData(response) {
  return response.data
}

exports.getAccessToken = function(appid, secret) {
  return axios.get(
    'https://api.weixin.qq.com/cgi-bin/token',
    {
      params: {
        grant_type: 'client_credential',
        appid: appid,
        secret: secret
      }
    }
  )
  .then(getResponseData)
}


exports.getUserProfile = function(access_token, openid) {
  return axios.get(
    'https://api.weixin.qq.com/cgi-bin/user/info',
    {
      params: {
        access_token: access_token,
        openid: openid,
        lang: 'zh_CN'
      }
    }
  )
  .then(getResponseData)
  .then((response) => {
    const { errcode, errmsg } = response

    console.log('getUserProfile')
    console.log(response)
    if (errcode && errmsg) {
      throw new Error(errmsg)
    }

    return response
  })
}

exports.getWebAccessToken = function(appid, secret, code) {
  return axios.get(
      'https://api.weixin.qq.com/sns/oauth2/access_token',
      {
        params: {
          appid,
          secret,
          code,
          grant_type: 'authorization_code'
        }
      })
    .then(getResponseData)
}

exports.getWebUserProfile = function(access_token, openid) {
  return axios.get(
    'https://api.weixin.qq.com/sns/userinfo',
    {
      params: {
        access_token: access_token,
        openid: openid,
        lang: 'zh_CN'
      }
    }
  )
  .then(getResponseData)
  .then((response) => {
    var { errcode, errmsg } = response

    console.log('getUserProfile')
    console.log(response)
    if (errcode && errmsg) {
      throw new Error(response.errmsg)
    }

    return response
  })
}

exports.webAccessTokenValid = function(access_token, openid) {
  return axios.get(
    'https://api.weixin.qq.com/sns/auth',
    {
      params: {
        access_token: access_token,
        openid: openid
      }
    }
  )
  .then(getResponseData)
}

exports.refreshWebAccessToken = function(appid, refresh_token) {
  return axios.get(
    'https://api.weixin.qq.com/sns/oauth2/refresh_token',
    {
      params: {
        appid: appid,
        grant_type: 'refresh_token',
        refresh_token: refresh_token
      }
    }
  )
  .then(getResponseData)
  .then(response => {
    console.log('refreshWebAccessToken')
    console.log(response)
    const { errcode, errmsg } = response
    if (errcode && errmsg) {
      throw new Error(errmsg)
    }

    return response
  })
}


/**
 * [downloadImg description]
 * @param  {string} url [image url]
 * @return {Promise}    [resolve(relative path), reject(error)]
 */
exports.downloadImg = function (url) {
  return axios({
    method: 'GET',
    url: url,
    responseType:'stream'
  })
  .then(response => {
    return new Promise((resolve, reject) => {
      const rootPath = '/client/temp'
      const filename = shortid.generate() + '.png'
      const fStream = fs.createWriteStream(path.join(__dirname, '../..', rootPath, filename))
      fStream.on('finish', () => {
        console.log('download finish')
        resolve(path.join('temp', filename))
      })

      fStream.on('error', (err) => {
        reject(err)
      })

      response.data.pipe(fStream)
    })
  })
}

exports.createMenu = function (access_token, params) {
  return axios
    .post(`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${access_token}`, params)
    .then(getResponseData)
    .then(res => {
      console.log(res)
      return res
    })
}

exports.getMenu = function (access_token) {
  return axios
    .get(`https://api.weixin.qq.com/cgi-bin/menu/get?access_token=${access_token}`)
    .then(getResponseData)
}

exports.getJsApiTicket = function(access_token) {
  return axios
    .get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`)
    .then(getResponseData)
}
